﻿using System.Data.SqlClient;
using System.Web;
using System.Web.Mvc;

namespace webcspa.Controllers
{
    public class LoginController : Controller
    {
        [HttpGet]
        public ActionResult Run()
        {
            var message = Request.QueryString["Message"];
            return View("Login", (object)message);
        }

        private const string connectionString = "Data Source=GORBUNOV-MS\\GORBUNOV;Initial Catalog=Users;Persist Security Info=True;User ID=sa;Password=vbif0192837465";

        [HttpPost]
        public ActionResult Login()
        {
            var login = Request.Form.Get("Login");
            var password = Request.Form.Get("Password");

            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();

                var command = connection.CreateCommand();
                command.CommandText = string.Format("select count(*) from users where login='{0}' and password='{1}'", login,
                                                    password);
                var usersCount = (int) command.ExecuteScalar();

                if (usersCount == 0)
                    return RedirectToAction("Run", new {Message = string.Format("Пользователь {0} не найден", login)});

                HttpContext.Response.SetCookie(new HttpCookie("user", login));
                return RedirectToAction("Run", "Data");
            }
        }
    }
}
